package com.gitee.wsl.prop

/**
 * @since 3.0.0
 */
interface PropContainer {
    operator fun <T> get(prop: Prop<T>): T?
    operator fun <T> get(prop: Prop<T>, defValue: T): T
    operator fun <T> set(prop: Prop<T>, value: T?)
    fun <T> clear(prop: Prop<T>)
    fun clearAll()
    fun <T> hasProp(prop: Prop<T>):Boolean = get(prop)!=null

    companion object{
        fun create() = PropContainerImpl()
    }
}

/**
 * @since 3.0.0
 */
open class PropContainerImpl : PropContainer {
    private val values: MutableMap<Prop<*>, Any> = HashMap(3)

    override fun <T> get(prop: Prop<T>): T? {
        return values[prop] as T?
    }

    override fun <T> get(prop: Prop<T>, defValue: T): T {
        val value = values[prop]
        return if (value != null) {
            value as T
        } else defValue
    }

    override fun <T> set(prop: Prop<T>, value: T?) {
        if (value == null) {
            values.remove(prop)
        } else {
            values[prop] = value
        }
    }

    override fun <T> clear(prop: Prop<T>) {
        values.remove(prop)
    }

    override fun clearAll() {
        values.clear()
    }

}